<template>
  <div class="file-list">
    <div class="breadcrumb-wrap flex">
      <span class="back flex justify-center" @click="goBack" v-if="breadcrumbList.length>0">
        <span>返回上一级</span>
        <span class="space"></span>|
        <span class="space"></span>
      </span>
      <Breadcrumb>
        <BreadcrumbItem
          :class="{pointer:breadcrumbList.length-1!=index}"
          v-for="(item,index) in breadcrumbList"
          :key="index"
          @click.native="crumbItemClick(item,index)"
        >{{item.name}}</BreadcrumbItem>
      </Breadcrumb>
    </div>
    <div class="deal clearfix">
      <div class="r data-botton">
        <Button @click="batchdDleteData">删除</Button>
        <Button type="primary" ghost @click="batchDownload">下载</Button>
        <Button type="primary" ghost @click="addFolder">新增文件夹</Button>
        <Button type="primary" ghost @click="synchronizeData">同步数据</Button>
        <Button type="primary" @click="open">上传数据</Button>
      </div>
      <Spin
        class="r pointer"
        v-show="showProgress"
        @click.native="uploadListShow=true"
        style="line-height:32px"
      >
        <Icon type="ios-loading" v-show="showProgressIcon" size="12" class="demo-spin-icon-load"></Icon>
        <span style="margin-right:20px" v-html="uploadingText"></span>
      </Spin>
      <div class="l r-spe flex items-center" style="cursor:pointer">
        <div class="search-input clearfix">
          <input type="text" class="aimind-hidden-input">
          <input type="password" class="aimind-hidden-input">
          <Input
            style="width:280px"
            autocomplete="off"
            search
            :maxlength="20"
            v-model.trim="keyWord"
            placeholder="请输入文件名或文件夹名称搜索"
            @on-enter="getNowData(1)"
            @on-search="getNowData(1)"
          />
        </div>
      </div>
    </div>
    <div class="table-data">
      <Table
        ref="selection"
        :columns="columns4"
        :data="fileData"
        class="table-form"
        @on-selection-change="tabelSelect"
      >
        <template slot-scope="{ row }" slot="name">
          <span class="ellipsis table-span-ellipsis" :title="row.name" v-if="row.directory">
            <a class="lan file" @click="fileChildren(row.fullFileName)">
              <Icon style="margin-right: 5px;" type="ios-folder"/>
              {{row.name}}
            </a>
          </span>
          <span class="ellipsis table-span-ellipsis" :title="row.name" v-else>{{row.name}}</span>
        </template>
        <template slot-scope="{ row }" slot="action">
          <div class="table-form-action-box" style="padding-right:10px">
            <span
              class="table-blue action-btn"
              v-if="row.name.indexOf('.zip')>0"
              @click="decompression(row.fullFileName)"
            >解压</span>
            <span class="table-blue action-btn" @click="renameItem(row)">重命名</span>
            <span class="table-blue action-btn" @click="moveItem(row)">移动</span>
            <span
              :class="['table-blue', 'action-btn', {'hid': row.dataType === '其他文件' || ((row.dataType === '文本文件' || row.dataType === '文档文件') && (row.exactDataSize / 1048576) > 10)}]"
              @click="viewDetail(row)"
            >查看</span>
            <span class="table-green action-btn" @click="downloadItem(row.fullFileName)">下载</span>
            <span class="table-red action-btn" @click="deleteItem(row.fullFileName)">删除</span>
          </div>
        </template>
      </Table>
      <Page
        transfer
        :current.sync="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        v-show="pagination.total>pagination.pageSize||pagination.pageSize>10"
        show-total
        show-sizer
        @on-change="changePageIndex"
        @on-page-size-change="changePageSize"
      />
    </div>
    <c-dialog
      title="上传数据"
      :bdTag.sync="dialog.add"
      ref="uploadDialog"
      :hidefoot="true"
      :styletemp="{'will-change':'transform','transition': `all ${translateSec}s linear`, 'transform': `translate(${translateX}px, ${translateY}px) scale(${scale})`}"
      :clazzName="'data-input'"
    >
      <Tabs value="localUpload">
        <TabPane label="本地上传" name="localUpload">
          <Form ref="dataForm" show-message :model="dataForm" :rules="rules" :label-width="90">
            <Spin fix v-if="fileLoadLoading">
              <Icon type="ios-loading" size="20" class="demo-spin-icon-load"></Icon>
              <div>正在载入文件</div>
            </Spin>
            <FormItem label="文件上传" prop="upload">
              <div class="basebtn flex">
                <!-- <label for="upload" class="iv-form-item__label" style="width: 100px;"><span style="color:red;margin-right:5px;">*</span>文件上传</label> -->
                <div class="upload-box relative flex-grow-1">
                  <div class="show-rule" v-if="!uploading">
                    <p style="margin-top:50px">
                      <i class="iconfont icon-upload" style="font-size:30px"></i>
                    </p>
                    <p class="btn-text">点击或将文件拖拽到这里上传</p>
                  </div>
                  <input
                    class="upload-input"
                    @change="fileChange($event)"
                    name="files"
                    type="file"
                    multiple="multiple"
                  >
                  <template v-if="uploading">
                    <div class="btn-text">点击或将文件拖拽到这里继续添加</div>
                    <ol class="iv-upload-list__item-name">
                      <li
                        class="iv-upload-list__item clearfix"
                        :key="k"
                        v-for="(v, k) in uploadList"
                      >
                        <span
                          style="max-width:325px"
                          class="l auto-wrap"
                          :title="`${v.file.name}`"
                        >{{v.file.name}}</span>
                        <span class="lan r" @click="removeUpload(k)">删除</span>
                      </li>
                    </ol>
                  </template>
                </div>
              </div>
            </FormItem>
            <FormItem label="创建文件夹" prop="createFolder">
              <RadioGroup v-model="dataForm.createFolder">
                <Radio label="1">创建</Radio>
                <Radio label="0">不创建</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem label="文件夹名称" prop="createFolderName" v-if="dataForm.createFolder==='1'">
              <Input v-model.trim="dataForm.createFolderName" :maxlength="20" placeholder="请输入文件夹名称"/>
            </FormItem>
          </Form>
        </TabPane>
      </Tabs>
      <div slot="footer" class="dialog-footer">
        <Button @click="dataDialogClose" style="margin-right: 10px;">取消</Button>
        <Button type="primary" @click="handleProgress">确认</Button>
      </div>
    </c-dialog>
    <c-dialog title="新建文件夹" :bdTag.sync="dialog.folder" :hidefoot="true" class="newui-part">
      <Form ref="folderForm" :model="folderForm" :rules="rules" :label-width="90">
        <FormItem label="文件夹名称" prop="folderName">
          <Input v-model.trim="folderForm.folderName" :maxlength="20" placeholder="请输入文件夹名称"/>
          <div class="folder-tip">支持中英文、数字和常见符号组合，不能超过20个字符</div>
        </FormItem>
      </Form>
      <div slot="footer" class="dialog-footer">
        <Button @click="cancelAddFolder" style="margin-right: 10px;">取消</Button>
        <Button type="primary" @click="addFolderYes">确认</Button>
      </div>
    </c-dialog>

    <!-- 文件编辑 -->
    <Modal
      class="page-file-model page-vscode-model"
      v-model="editFileStatus"
      fullscreen
      title="编辑文件"
      @on-cancel="editFileCodeCancel"
    >
      <VsCodeMenu v-show="editFileStatus" :defaultExpandFilePath="defaultExpandFilePath" @setValue="setValue"/>
      <VsCodeEditor
        :options="vscodeOption"
        :hasMenu="true"
        ref="vsCodeEditor"
        v-if="editFileStatus"
      />
      <div class="demo-drawer-footer">
        <Button style="margin-right: 8px" @click="editFileCodeCancel">取消</Button>
        <Button type="primary" style="margin-right: 8px" @click="editFileBtn(false)">保存</Button>
        <Button type="primary" @click="editFileBtn(true)">保存并关闭</Button>
      </div>
    </Modal>

    <upload-list :uploadListShow.sync="uploadListShow"></upload-list>

    <!-- 重命名文件夹 -->
    <Modal footer-hide title="重命名文件夹" class-name="vertical-center-modal" v-model="renameFileVisible" width="500px">
      <form-model
        ref="renameModel"
        :options="renameItemOptions"
        @cancelHandler="renameFileVisible=false"
        @okHandler="renameOkHandler"
      />
    </Modal>

    <!-- 移动文件或文件夹 -->
    <Modal
      v-model="moveVisible"
      @on-visible-change="moveVisibleChange"
      class-name="vertical-center-modal"
      width="360"
      title="移动文件或文件夹">
      <Tree
        class="move-tree"
        :data="moveTreeData"
        @on-select-change="changeMoveTreeSelected"
        :load-data="loadMoveTreeData"
      ></Tree>

      <div slot="footer">
        <Button type="primary" @click="okMove">确定</Button>
        <Button @click="cancelMove">取消</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  getDirFilesInfo,
  deleteObject,
  createFolder,
  preview,
  edit,
  decompression,
  rename,
  getListSonDir,
  move
} from 'http/api/file';

import FormModel from 'pages/Common/FormModel';
import { renameItemOptions } from './utils/constant.js';
import VsCodeMenu from 'pages/Common/VsCodeMenu';
import CDialog from './children/CDialog';
import UploadList from './UploadList';
import httpConfig from 'http/config';
import { formatFileSize } from 'assets/scripts/common';
import { createNamespacedHelpers } from 'vuex';
import { uploadStatus } from 'assets/scripts/code';

const VsCodeEditor = () => import('pages/Common/VsCodeEditor');
const { mapState, mapMutations } = createNamespacedHelpers('files');
const regEn = /[#+=%&?]/im;
const regFolder = /[\\/]/im;
export default {
  created () {
    if (window.sessionStorage.getItem('pageHistorty')) {
      this.pageHistorty = JSON.parse(
        window.sessionStorage.getItem('pageHistorty')
      );
    } else {
      this.pageHistorty = [];
      window.sessionStorage.setItem('pageHistorty', JSON.stringify([]));
    }
    // console.log(this.pageHistorty);
    this.getNowData();
  },
  data () {
    var folderCheck = (rule, value, callback) => {
      if (regFolder.test(value) || regEn.test(value)) {
        callback(new Error('文件夹名称不能包含特殊字符'));
      } else if (value.length > 20) {
        callback(new Error('文件夹名称不能超过20个字符'));
      } else {
        callback();
      }
    };
    return {
      DEFAULTURL: '/home/file',
      dialog: {
        // 控制dialog显示
        add: false,
        folder: false
      },
      pagination: {
        total: 0, // 一共多少
        pageSize: 10, // 每页数量
        currentPage: 1, // 当前页
        keyWord: ''
      },
      keyWord: '',
      breadcrumbList: [],
      pageHistorty: [],
      mutliFileList: [],
      // dialog出现动画
      translateSec: 0,
      scale: 1,
      translateX: 0,
      translateY: 0,
      // 文件上传表单
      dataForm: {
        createFolder: '0',
        createFolderName: ''
      },
      // 新增文件表单
      folderForm: {
        folderName: ''
      },
      idList: [], // 批量删除容器
      uploading: false, // 是否在进行上传操作，文件列表中是否有文件
      fileLoadLoading: false,
      uploadListShow: false,
      uploadingText: '',
      uploadList: [], // 上传文件列表
      uplist: [], // 待传给接口的信息
      showProgress: false,
      showProgressIcon: false,
      rules: {
        createFolderName: [
          {
            required: true,
            message: '请输入文件夹名称',
            trigger: 'blur'
          },
          {
            validator: folderCheck,
            trigger: 'blur'
          }
        ],
        folderName: [
          {
            required: true,
            message: '请输入文件夹名称',
            trigger: 'blur'
          },
          {
            validator: folderCheck,
            trigger: 'blur'
          }
        ]
      },
      // lookDetailStatus: false,
      lookDetailInfo: {},
      editFile: {
        editFileContent: 'aimind',
        fullFileName: '/'
      },
      editFileStatus: false,
      // 编辑器配置
      vscodeOption: {
        value: '',
        language: 'python'
      },
      defaultExpandFilePath: '/',
      fileData: [],
      columns4: [
        {
          type: 'selection',
          width: 60
        },
        {
          title: '文件名称',
          key: 'name',
          sortable: true,
          slot: 'name'
        },
        {
          title: '文件大小',
          key: 'dataSize',
          width: '120px'
        },
        {
          title: '创建时间',
          key: 'createTime',
          width: '200px'
        },
        {
          title: '操作类型',
          key: 'dataType',
          width: '120px'
        },
        {
          title: '操作',
          key: 'action',
          width: '360px',
          slot: 'action'
        }
      ],

      renameItemOptions,
      renameFileVisible: false,
      renameFilePath: '',

      moveFilePath: '',
      moveVisible: false,
      moveTreeData: [
        {
          title: '根目录',
          loading: false,
          children: [],
          fullFileName: '\\'
        }
      ],
      moveToPath: ''
    };
  },
  methods: {
    isWord (name) {
      let suffix = '';
      let result
      let flieArr

      try {
        flieArr = name.split('.');
        suffix = flieArr[flieArr.length - 1];
      } catch (err) {
        suffix = '';
      }

      result = ['doc', 'docx'].some(function (item) {
        return item === suffix;
      })

      return result
    },

    goBack () {
      if (this.$route.query.path) {
        this.pagination.currentPage = this.pageHistorty.pop();
        window.sessionStorage.setItem(
          'pageHistorty',
          JSON.stringify(this.pageHistorty)
        );
        // console.log(this.pageHistorty);
        let path = this.$route.query.path;
        let temp = path.substring(0, path.lastIndexOf('/'));
        this.$router.replace({
          path: this.DEFAULTURL,
          query: {
            path: temp
          }
        });
      }
    },
    crumbItemClick (item, index) {
      if (index === this.breadcrumbList.length - 1) {
        return;
      }

      this.pagination.currentPage = this.pageHistorty[index + 1];
      this.pageHistorty = this.pageHistorty.slice(0, index + 1);
      window.sessionStorage.setItem(
        'pageHistorty',
        JSON.stringify(this.pageHistorty)
      );
      // console.log(this.pageHistorty);
      // 回退时不需要记录历史记录
      this.$router.replace({
        path: this.DEFAULTURL,
        query: {
          path: item.path
        }
      });
    },
    getNowData (page) {
      this.breadcrumbList = [];
      if (this.$route.query.path) {
        let routepath = this.$route.query.path.replace(/\\/g, '/');
        let pathList = routepath
          .substring(routepath.indexOf('/') + 1)
          .split('/');

        for (let i = 0; i < pathList.length; i++) {
          let obj = {
            name: pathList[i],
            path: ''
          };
          for (let j = 0; j <= i; j++) {
            obj.path += '/' + pathList[j];
          }
          this.breadcrumbList.push(obj);
        }
      }
      // 在浏览器回退时保持页码正常
      if (this.breadcrumbList.length < this.pageHistorty.length) {
        this.pagination.currentPage =
          this.pageHistorty.length > 0
            ? this.pageHistorty[this.breadcrumbList.length]
            : 1;
        this.pageHistorty = this.pageHistorty.slice(
          0,
          this.breadcrumbList.length
        );
        window.sessionStorage.setItem(
          'pageHistorty',
          JSON.stringify(this.pageHistorty)
        );
      }
      // console.log(this.pageHistorty);
      this.getBucket(page);
    },
    deleteItem (fullFileName) {
      this.mutliFileList.push(encodeURIComponent(fullFileName.replace(/\\/g, '/')));

      this.mutliFileList = [...new Set(this.mutliFileList)];
      this.$Modal.confirm({
        title: '确认要删除吗',
        content: '<p>数据删除后不可恢复，请确保文件是未在使用</p>',
        onOk: async () => {
          await deleteObject({
            fullFileNames: fullFileName.replace(/\\/g, '/')
          });
          this.pagination.currentPage =
            this.pagination.total -
              this.pagination.pageSize * (this.pagination.currentPage - 1) ===
              this.mutliFileList.length && this.pagination.currentPage > 1
              ? this.pagination.currentPage - 1
              : this.pagination.currentPage;
          this.mutliFileList = [];
          this.getBucket();
        }
      });
    },
    downloadItem (fullFileName) {
      let userName = JSON.parse(window.localStorage.userInfo).login;
      let fileName = encodeURIComponent(fullFileName.replace(
        /\\/g,
        '/'
      ))

      window.open(
        `${
          httpConfig.baseURL
        }/datavolum/download?userName=${userName}&fullFileNames=${fileName}`
      );
    },
    // 表单数据单选
    tabelSelect (selection, row) {
      this.mutliFileList = [];
      selection.forEach(el => {
        this.mutliFileList.push(encodeURIComponent(el.fullFileName.replace(/\\/g, '/')));
      });
    },
    // 顶部批量删除数据
    async batchdDleteData () {
      if (this.mutliFileList.length === 0) {
        this.$Message.warning('请选择要删除的文件');
        return;
      }
      this.$Modal.confirm({
        title: '确认要删除吗',
        content: '<p>数据删除后不可恢复，请确保文件是未在使用</p>',
        onOk: async () => {
          let list = this.mutliFileList.map(
            item => decodeURIComponent(item)
          )
          await deleteObject({
            fullFileNames: list.join(',')
          });
          this.pagination.currentPage =
            this.pagination.total -
              this.pagination.pageSize * (this.pagination.currentPage - 1) ===
              this.mutliFileList.length && this.pagination.currentPage > 1
              ? this.pagination.currentPage - 1
              : this.pagination.currentPage;

          this.mutliFileList = [];
          this.getBucket();
        },
        onCancel: () => {}
      });
    },
    // 顶部批量下载
    batchDownload () {
      let userName = JSON.parse(window.localStorage.userInfo).login;
      if (this.mutliFileList.length === 0) {
        this.$Message.warning('请选择要下载的文件');
        return;
      }
      window.open(
        `${
          httpConfig.baseURL
        }/datavolum/download?userName=${userName}&fullFileNames=${this.mutliFileList.join(
          ','
        )}`
      );
    },
    // 顶部新建文件夹
    addFolder () {
      this.dialog.folder = true;
      this.folderForm.folderName = '';
    },
    addFolderYes () {
      let routepath = this.$route.query.path
        ? this.$route.query.path.replace(/\\/g, '/')
        : '/';
      this.$refs.folderForm.validate(async valid => {
        if (valid) {
          let folderName = this.folderForm.folderName;
          await createFolder({
            currentDir: routepath,
            createFolderName: folderName
          });
          this.dialog.folder = false;
          this.getBucket();
        } else {
          return false;
        }
      });
    },
    renameItem (row) {
      this.renameFilePath = row.fullFileName
      this.renameFileVisible = true;
      this.renameItemOptions.model.newName = row.name;
    },
    // 重新命名文件夹
    async renameOkHandler (model) {
      await rename({
        fullFileName: this.renameFilePath,
        newName: model.newName
      })
      this.$Message.success('重命名成功');
      this.renameFileVisible = false;
      this.getBucket()
    },
    async moveItem (row) {
      this.moveFilePath = row.fullFileName
      this.moveVisible = true
    },
    changeMoveTreeSelected (val) {
      this.moveToPath = val[0] === undefined ? '' : val[0].fullFileName
    },
    async loadMoveTreeData (item, callback) {
      let { data } = await getListSonDir({
        fullFileName: item.fullFileName
      })

      let fromData = JSON.parse(
        JSON.stringify(data)
          .replace(/name/g, 'title')
      );

      for (let i = 0; i < fromData.length; i++) {
        const ele = fromData[i];
        ele.loading = false
        ele.children = []
      }

      callback(fromData);
    },
    async okMove () {
      if (this.moveToPath === '') {
        this.$Message.warning('请选择要移动到的文件夹')
        return false
      }

      let moveFilePath = this.moveFilePath

      if (moveFilePath === this.moveToPath) {
        this.$Message.warning('文件夹路径重叠')
        return false
      }

      moveFilePath = moveFilePath.replace(/\//g, '\\')

      await move({
        fullFileName: moveFilePath,
        newDirFileName: this.moveToPath
      })

      this.$Message.success('移动成功')
      this.moveVisible = false
      this.getBucket()
    },
    cancelMove () {
      this.moveTreeData = [
        {
          title: '根目录',
          loading: false,
          children: [],
          fullFileName: '\\'
        }
      ]

      this.moveVisible = false
    },

    moveVisibleChange (val) {
      if (!val) {
        this.moveTreeData = [
          {
            title: '根目录',
            loading: false,
            children: [],
            fullFileName: '\\'
          }
        ]
      }
    },

    async decompression (fullFileName) {
      await decompression({
        fullFileName: fullFileName
      });
      this.getNowData();
    },
    cancelAddFolder () {
      this.dialog.folder = false;
      this.folderForm.folderName = '';
    },
    changePageIndex (page) {
      this.pagination.currentPage = page;
      this.getBucket();
    },
    changePageSize (size) {
      this.pagination.pageSize = size;
      this.changePageIndex(1);
    },
    // 点击上传数据按钮
    open () {
      this.uploadList = [];
      this.dataForm = {
        createFolder: '0',
        createFolderName: ''
      };
      this.dialog.add = true;
    },
    // 关闭dialog
    dataDialogClose () {
      this.uploadList = [];
      this.dataForm.createFolder = '0';
      this.uploading = false;
      this.dialog.add = false;
    },
    // 删除文件
    removeUpload (k) {
      this.uploadList.splice(k, 1);
      if (this.uploadList.length === 0) {
        this.uploading = false;
      }
    },
    // 监听文件上传变化
    fileChange (el) {
      let files = el.target.files;
      this.fileChangeFuc(files);
      el.target.value = '';
    },
    fileChangeFuc (files) {
      this.fileLoadLoading = true;
      let errorStr = '';
      let sucFiles = [];
      if (files && files.length > 0) {
        let elFilesLength = files.length;
        for (let i = 0; i < elFilesLength; i++) {
          let fileName = files[i].name;
          let fileSize = files[i].size;
          if (fileName.length > 230) {
            errorStr = `${errorStr}${fileName}文件名不能大于230个字符;`;
          } else if (fileSize > 104857600) {
            errorStr = `${errorStr}${fileName}单一文件不能超过100M;`;
          } else {
            sucFiles.push(files[i]);
          }
        }
      } else {
        this.fileLoadLoading = false;
        return;
      }
      if (errorStr) {
        this.$Message.warning(errorStr.substring(0, errorStr.length - 1));
        if (sucFiles.length === 0) {
          this.fileLoadLoading = false;
          return;
        }
      }
      if (sucFiles.length > 0) {
        this.uploading = true;
      }
      this.fileLst(sucFiles);
    },
    // 处理文件列表函数
    fileLst (files) {
      for (let i = 0; i < files.length; i++) {
        this.fileAdd(files[i]);
      }
    },
    // 文件添加
    fileAdd (file) {
      let reader = new FileReader();
      reader.onerror = e => {
        if (
          e &&
          e.target &&
          e.target.error &&
          e.target.error.message === 'File could not be read' &&
          navigator.userAgent.indexOf('Firefox') > 0
        ) {
          this.$Message.warning(
            `文件:${file.name} 暂不支持上传，建议使用Chrome重试`
          );
        } else {
          this.$Message.warning('目前不支持文件夹上传');
        }
        this.fileLoadLoading = false;
      };
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.uploadList.push({
          file
        });
        this.fileLoadLoading = false;
      };
    },
    // 上传文件提交
    handleProgress () {
      this.setErrorList([]);
      this.showProgressIcon = true;
      this.showProgress = true;
      let routepath = this.$route.query.path
        ? this.$route.query.path.replace(/\\/g, '/')
        : '/';
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if (this.uploadList.length === 0) {
            this.$Message.warning('请选择文件上传');
            return;
          }
          let upObj = {};
          let isCreateFolder = false;
          if (this.dataForm.createFolder === '1') {
            isCreateFolder = true;
          }
          for (let i in this.uploadList) {
            let size = formatFileSize(this.uploadList[i].file.size, 0);
            upObj = {
              name: this.uploadList[i].file.name, // 文件名称
              dataSize: size, // 文件大小
              uploadPercentage: 0, // 上传进度
              uploadStatus: uploadStatus.NOSTART, // 上传状态
              file: this.uploadList[i], // 要上传的文件
              isCreateFolder: isCreateFolder,
              currentDir: routepath, // 当前路径
              createFolderName: this.dataForm.createFolderName // 要创建的文件名
            };
            this.uplist.push(upObj);
          }
          this.setUploadData([...this.uploadData, ...this.uplist]);

          this.uplist = [];
          this.$Message.warning('文件上传中，请不要关闭页面');
          setTimeout(() => {
            this.dialog.add = false;
            this.uploading = false;
          }, 600);
          // todo 进行上传操作
          this.$emit('triggerUp');
        } else {
          this.$Message.error('上传失败');
        }
      });
    },
    // 点击每条上的编辑
    async viewDetail (row) {
      let { name, fullFileName, dataType, exactDataSize } = row;

      switch (dataType) {
        case '文本文件':
          if (exactDataSize / 1048576 > 10) {
            return
          }

          fullFileName = fullFileName.replace(/\\/g, '/');
          this.editFile.fullFileName = fullFileName;
          const result = await preview({
            fullFileName: fullFileName
          });
          this.editFile.editFileContent = result.data;
          // 替换编辑器vscode
          if (fullFileName.includes('.py')) {
            this.vscodeOption.language = 'python';
          } else if (fullFileName.includes('.json')) {
            this.vscodeOption.language = 'json';
          } else if (fullFileName.includes('.sh')) {
            this.vscodeOption.language = 'shell';
          } else if (fullFileName.includes('.java')) {
            this.vscodeOption.language = 'java';
          } else {
            this.vscodeOption.language = 'javascript';
          }

          this.vscodeOption.value = result.data;
          this.defaultExpandFilePath = fullFileName;
          this.editFileStatus = true;
          break;

        case '文档文件':
          if (exactDataSize / 1048576 > 10) {
            return
          }

          if (this.isWord(name)) {
            window.open(
              `${
                httpConfig.baseURL
              }/datavolum/previewDoc?fullFileName=${encodeURIComponent(fullFileName.replace(
                /\\/g,
                '/'
              ))}`
            );
          }
          break;

        case '其他文件':
          break;

        default:
          break;
      }
    },

    // 关闭编辑器
    editFileCodeCancel () {
      this.editFileStatus = false;
      // 销毁实例
      this.$refs.vsCodeEditor.dispose();
    },

    // 切换编辑器的文件
    setValue (params) {
      let { fullFileName, data } = params;
      this.editFile.fullFileName = fullFileName;
      this.$refs.vsCodeEditor.setValue(data);
    },

    // 编辑器确定
    async editFileBtn (boolean) {
      let code = this.$refs.vsCodeEditor.getValue();
      if (!this.editFile.fullFileName) {
        this.$Message.error('请选择可用的文件名');
        return;
      }
      await edit({
        fullFileName: this.editFile.fullFileName,
        content: code
      });

      this.$Message.success('修改成功');

      if (boolean) {
        this.editFileCodeCancel();
      }
    },

    async synchronizeData () {
      const msg = this.$Message.loading({
        content: '正在同步',
        duration: 0
      });
      await this.getBucket();
      setTimeout(msg, 100);
      this.$Message.success('同步成功');
    },
    // 获取数据集下的文件
    async getBucket (page) {
      let data = {
        currentDir: this.$route.query.path ? this.$route.query.path : '/',
        currentPage: page === undefined ? this.pagination.currentPage : page,
        pageSize: this.pagination.pageSize
      };
      if (this.keyWord) {
        data.keyWord = this.keyWord;
      }
      const result = await getDirFilesInfo(data);
      this.fileData = this.judgeFile(result.fileAttributes);

      this.pagination.total = result.total;
    },
    fileChildren (path) {
      path = encodeURIComponent(path.replace(/\\/g, '/'));

      if (path) {
        this.pageHistorty.push(this.pagination.currentPage);
        window.sessionStorage.setItem(
          'pageHistorty',
          JSON.stringify(this.pageHistorty)
        );
        this.pagination.currentPage = 1; // 解决子目录中的分页问题

        this.$router.push(`${this.DEFAULTURL}?path=${path}`);
      } else {
        this.$router.push(`${this.DEFAULTURL}`);
      }
    },
    // 判断是否是文件夹
    judgeFile (data) {
      if (!Array.isArray(data)) {
        return [];
      }
      const result = data.map((item, index) => {
        // if (item.directory) {
        //   item._disabled = true
        // }
        item.fullFileName = item.fullFileName.replace(/\\/g, '/');
        return item;
      });
      return result;
    },
    ...mapMutations(['setUploadData', 'setErrorList'])
  },
  components: {
    CDialog,
    UploadList,
    FormModel,
    VsCodeEditor,
    VsCodeMenu
  },
  computed: {
    computedUploadData () {
      let uplist = [...this.uploadData, ...this.localListUse];
      return uplist;
    },
    ...mapState({
      uploadData: state => state.uploadData,
      localListUse: state => state.localListUse,
      errorList: state => state.errorList
    })
  },
  watch: {
    computedUploadData (uplist) {
      const hasDoneList = uplist.filter(item => {
        if (
          item.uploadStatus === uploadStatus.SUCCESS ||
          item.uploadStatus === uploadStatus.FAIL
        ) {
          return true;
        }
      });
      const leftDataLength = uplist.length - hasDoneList.length || 0;
      const eruptNum = leftDataLength > 5 ? 5 : leftDataLength;
      if (leftDataLength > 0 || this.errorList.length > 0) {
        this.showProgress = true;
      } else {
        this.showProgress = false;
      }
      if (leftDataLength === 0) {
        this.showProgressIcon = false;
        this.getBucket();
      }
      if (this.errorList.length > 0) {
        if (leftDataLength > 0) {
          this.uploadingText = `正在上传${eruptNum}/${leftDataLength}<span style="color:red;margin-left:10px" }>上传失败${
            this.errorList.length
          }</span>`;
        } else {
          this.uploadingText = `<span style="color:red;margin-left:10px" }>上传失败${
            this.errorList.length
          }</span>`;
        }
      } else {
        this.uploadingText = `正在上传${eruptNum}/${leftDataLength}`;
      }
    },
    $route (val) {
      this.getNowData();
    }
  }
};
</script>

<style rel="stylesheet/less" lang="less" scoped>
@import "../../assets/theme/themeBlue.less";
.deal {
  margin: 10px 0;
  .data-botton {
    button {
      margin-right: 10px;
    }
  }
  .search-input {
    input {
      height: 40px;
      width: 230px;
      line-height: 40px;
      border: none;
      padding: 0 15px 0 10px;
      outline: none;
      background: transparent;
    }
    .search-btn {
      position: relative;
      padding-right: 10px;
      line-height: 40px;
      cursor: pointer;
      width: 74px;
      height: 40px;
      &:before {
        content: "";
        position: absolute;
        top: 10px;
        left: -10px;
        width: 1px;
        height: 20px;
        background: #dcdfe6;
      }
      .icon {
        margin-right: 5px;
      }
    }
  }
}

.breadcrumb-wrap {
  .back {
    margin-left: 5px;
    font-size: 13px;
    color: @primary;
    cursor: pointer;
    line-height: 22px;
    height: 22px;
    .ivu-icon {
      line-height: 21px;
    }
    .space {
      margin: 0 5px;
    }
  }
}
.table-data {
  text-align: center;
  min-width: 900px;
  .table-form {
    margin-bottom: 10px;
    .action-btn {
      margin-right: 10px;
    }
    .hid {
      opacity: 0.5;
    }
  }
}

.upload-box {
  height: 180px;
  border: 1px dashed @primary;
  border-radius: 6px;
  cursor: pointer;
  .show-rule {
    text-align: center;
  }
  .btn-text {
    text-align: center;
    color: #909399;
    font-size: 14px;
  }
  .upload-input {
    position: absolute;
    cursor: pointer;
    opacity: 0;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
  }
  .iv-upload-list__item-name {
    position: relative;
    box-sizing: border-box;
    padding: 0 20px;
    max-height: 140px;
    overflow: auto;
    z-index: 10;
  }
  .iv-upload-list__item {
    line-height: 20px;
    &:hover {
      background-color: #f5f7fa;
    }
    .lan {
      color: @primary;
    }
  }
}

.newui-part {
  .folder-tip {
    color: #ccc;
  }
}
.detail-drawer {
  .drawer-title {
    max-width: 90%;
    padding-bottom: 10px;
    font-size: 18px;
  }
  .drawer-section {
    font-size: 16px;
    font-weight: 600;
    line-height: 50px;
  }
  .drawer-profile {
    color: @content-text;
    font-size: 14px;
    margin-top: 10px;
    .ivu-row {
      line-height: 32px;
      .ivu-col-span-6 {
        text-align: right;
        padding-right: 20px;
      }
    }
  }
}
.textarea-input {
  display: inline-block;
  width: 100%;
  height: 32px;
  line-height: 1.5;
  padding: 4px 7px;
  font-size: 12px;
  border: 1px solid #dcdee2;
  border-radius: 4px;
  color: #515a6e;
  background-color: #fff;
  background-image: none;
  position: relative;
  cursor: text;
  transition: border 0.2s ease-in-out, background 0.2s ease-in-out,
    box-shadow 0.2s ease-in-out;
  &:hover {
    border-color: #57a3f3;
  }
}
.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
.dialog-footer {
  border-top: 1px solid #e8eaec;
  padding: 10px 15px 0;
  text-align: right;
  width: calc(100% + 32px);
  margin-left: -16px;
}
</style>
<style lang="less">
@import "../../assets/theme/themeBlue.less";
.deal {
  .search-input {
    .ivu-input-suffix i {
      color: @primary;
    }
  }
}
.page-file-model .ivu-modal-footer {
  display: none;
  padding: 6px 18px 20px;
  border-top: none;

  text-align: left;

  .ivu-select {
    width: 100px;
  }
}
.page-file-model .demo-drawer-footer {
  z-index: 99;
}
.page-file-model .vue-codemirror {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
.page-file-model .CodeMirror {
  height: 100%;
}
.file-list {
  .ivu-table-body {
    max-height: 400px;
    overflow-y: auto;
    overflow-x: hidden;
  }
}
</style>
